<template>
  <el-card style="height: 80px">
    <el-form :inline="true" class="form">
      <el-form-item label="用户名:">
        <el-input placeholder="请你输入搜索用户名" v-model="keyword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="default"
          :disabled="keyword ? false : true"
          @click="search"
          >搜索</el-button
        >
        <el-button type="primary" size="default" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0px">
    <el-button type="primary" size="default" @click="addUser"
      >添加用户</el-button
    >
    <el-button type="primary" size="default" @click="batchDelete" :disabled="idList.length==0">批量删除</el-button>
    <!-- table展示用户信息 -->
    <el-table :data="userArr" style="margin: 10px 0px" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <el-table-column label="ID" align="center" prop="id"></el-table-column>
      <el-table-column
        label="用户名字"
        align="center"
        prop="username"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户名称"
        align="center"
        prop="name"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户角色"
        align="center"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="300px" align="center">
        <template #="{ row, $index }">
          <el-button type="primary" size="small" icon="User" @click="setRole(row)"
            >分配角色</el-button
          >
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateUser(row)"
            >编辑</el-button
          >
          <el-popconfirm :title="`你确定要删除${row.username}?`" width="260px" @confirm="deleteRole(row.id)">
            <template #reference>
              <el-button type="primary" size="small" icon="Delete"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 7, 9, 11]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @current-change="getHasUser"
      @size-change="handler"
    />
  </el-card>
  <!-- 抽屉结构:完成添加新的用户账号|更新已有的账号信息 -->
  <el-drawer v-model="drawer">
    <!-- 头部标题:将来文字内容应该动态的 -->
    <template #header>
      <h4>{{userParams.id?'修改用户':'添加用户'}}</h4>
    </template>
    <!-- 身体部分 -->
    <template #default>
      <el-form ref="formRef" :rules="rules" :model="userParams">
        <el-form-item label="用户姓名" prop="username">
          <el-input
            placeholder="请您输入用户姓名"
            v-model="userParams.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input
            placeholder="请您输入用户昵称"
            v-model="userParams.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
          <el-input
            placeholder="请您输入用户密码"
            v-model="userParams.password"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </template>
  </el-drawer>
  <!-- 抽屉结构:用户某一个已有的账号进行职位分配 -->
  <el-drawer v-model="drawer1">
    <template #header>
      <h4>分配角色(职位)</h4>
    </template>
    <template #default>
      <el-form>
        <el-form-item label="用户姓名">
          <el-input v-model="userParams.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="职位列表">
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
          <!-- 显示职位的的复选框 -->
          <el-checkbox-group v-model="userRole" @change="handleCheckedCitiesChange">
            <el-checkbox
              v-for="(role, index) in allRole"
              :key="role.id"
              :label="role"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer1=false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from "vue";
import { reqUserInfo, reqAddOrUpdateUser,reqAllRole,reqSetUserRole,reqRemoveUser,reqSelectUser } from "@/api/acl/user/index";
import { UserResponseData, User,AllRoleResponseData,RoleData,SetRoleData } from "@/api/acl/user/type";
import { ElMessage } from "element-plus";
import useLayOutSettingStore from '@/store/modules/setting'
let settingStore = useLayOutSettingStore()
let keyword = ref<string>("");
let drawer = ref<boolean>(false);
let drawer1 = ref<boolean>(false);
let pageNo = ref<number>(1);
let pageSize = ref<number>(5);
let total = ref<number>(0);
let userArr = ref<User[]>([]);
let formRef = ref<any>();
let userParams = reactive<User>({
  username: "",
  name: "",
  password: "",
});
let allRole = ref<RoleData[]>([])
let userRole = ref<RoleData[]>([])
const checkAll = ref(false)
const isIndeterminate = ref(true)
const idList = ref<any>([])
// 校验用户名
const validateUserName = (rule: any, value: any, callback: any) => {
  if (value == "") {
    callback(new Error("请您输入用户姓名"));
  } else {
    if (userParams.username !== "") {
      if (!formRef.value) return;
      formRef.value.validateField("username", () => null);
    }
    callback();
  }
};
// 校验昵称
const validateName = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请您输入用户昵称"));
  } else {
    if (userParams.name !== "") {
      if (!formRef.value) return;
      formRef.value.validateField("name", () => null);
    }
    callback();
  }
};
// 校验密码
const checkPwd = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请您输入用户密码"));
  } else {
    if (userParams.password !== "") {
      if (!formRef.value) return;
      formRef.value.validateField("password", () => null);
    }
    callback();
  }
};
const rules = reactive({
  username: [{ validator: validateUserName, trigger: "blur", required: true }],
  name: [{ validator: validateName, trigger: "blur", required: true }],
  password: [{ validator: checkPwd, trigger: "blur", required: true }],
});
onMounted(() => {
  getHasUser();
});
const getHasUser = async (page = 1) => {
  pageNo.value = page;
  let res: UserResponseData = await reqUserInfo(
    pageNo.value,
    pageSize.value,
    keyword.value
  );
  if (res.code == 200) {
    userArr.value = res.data.records;
    total.value = res.data.total;
  }
};
const handler = () => {
  getHasUser();
};
// 添加用户
const addUser = () => {
  Object.assign(userParams, {
    username: "",
    name: "",
    password: "",
    id:0
  });
  drawer.value = true;
  nextTick(() => {
    formRef.value.clearValidate('username');
    formRef.value.clearValidate('name');
    formRef.value.clearValidate('password');
  });
};
// 编辑
const updateUser = (row: User) => {
  Object.assign(userParams,row)
  drawer.value = true;
  nextTick(() => {
    formRef.value.clearValidate('username');
    formRef.value.clearValidate('name');
    formRef.value.clearValidate('password');
  });
};
// 取消
const cancel = () => {
  drawer.value = false;
};
// 确定
const confirm = async () => {
  await formRef.value.validate();
  let res = await reqAddOrUpdateUser(userParams);
  if (res.code == 200) {
    ElMessage({
      type: "success",
      message: userParams.id ? "修改成功" : "添加成功",
    });
    drawer.value = false;
    getHasUser(userParams.id ? pageNo.value : 1);
  } else {
    ElMessage({
      type: "error",
      message: userParams.id ? "修改失败" : "添加失败",
    });
  }
};
// 获取分配角色列表
const setRole = async (row:User)=>{
  Object.assign(userParams,row)
  drawer1.value = true
  let res:AllRoleResponseData = await reqAllRole((userParams.id as number))
  if(res.code==200){
    allRole.value = res.data.allRolesList
    userRole.value = res.data.assignRoles
  }
}
// 全选
const handleCheckAllChange = (val: boolean) => {
  userRole.value = val ? allRole.value : []
  isIndeterminate.value = false
}
// 返选
const handleCheckedCitiesChange = (value: string[])=>{
  const checkedCount = value.length
  checkAll.value = checkedCount === allRole.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < allRole.value.length
}
// 分配角色
const save = async ()=>{
  let data:SetRoleData = {
    userId: (userParams.id as number),
    roleIdList:userRole.value.map(item=>{
      return (item.id as number)
    })
  }
  let res = await reqSetUserRole(data)
  if(res.code==200){
    ElMessage({type:'success',message:'分配成功'})
    drawer1.value = false
    getHasUser(pageNo.value)
  }
}
// 删除
const deleteRole = async (id:number)=>{
 let res =  await reqRemoveUser(id)
 if(res.code==200){
  ElMessage({type:'success',message:'删除成功'})
  getHasUser( userArr.value.length>1?pageNo.value:pageNo.value-1)
 }
}
// 多选
const handleSelectionChange = (val:any) => {
  console.log(val)
  idList.value = val.map((item:any)=>{
    return item.id
  })
}
// 批量删除
const batchDelete = async ()=>{
  let res:any = await reqSelectUser(idList.value)
  if(res.code==200){
    ElMessage({type:'success',message:'删除成功'})
    getHasUser( userArr.value.length>1?pageNo.value:pageNo.value-1)
  }
}
// 搜索
const search = ()=>{
  getHasUser()
  keyword.value = ''
}
// 重置
const reset = ()=>{
  settingStore.refsh =!settingStore.refsh
}
</script>
<style lang="scss" scoped></style>
